import React, { useContext, useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Table, InputNumber, Input, Button, Form, Tabs, Card, message, Space } from 'antd';
import { FormInstance } from 'antd/lib/form';

import MfgMtlSearch from './MfgMtlSearch';
import MfgMtlUpdate from './MfgMtlUpdate';
import MfgMtiSearchTui from './MfgMtiSearchTui';

const EditableContext = React.createContext<FormInstance<any> | null>(null);

const { TabPane } = Tabs;
//形参类型
interface Item {
  key: string;
  pickPer: string;
  remark: string;
  department: string;
  pickDate: string;
}

interface EditableRowProps {
  index: number;
}

const EditableRow: React.FC<EditableRowProps> = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  children: React.ReactNode;
  dataIndex: keyof Item;
  record: Item;
  handleSave: (record: Item) => void;
}

const EditableCell: React.FC<EditableCellProps> = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<Input>(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing) {
      inputRef.current!.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({ [dataIndex]: record[dataIndex] });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.log('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{ margin: 0 }}
        name={dataIndex}
        rules={[
          {
            required: true,
            message: `请输入${title} .`,
          },
        ]}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div className="editable-cell-value-wrap" style={{ paddingRight: 24 }} onClick={toggleEdit}>
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

type EditableTableProps = Parameters<typeof Table>[0];

interface DataType {
  key: React.Key;
  pickPer: string;
  remark: string;
}

interface EditableTableState {
  dataSource: DataType[];
  count: number;
}

type ColumnTypes = Exclude<EditableTableProps['columns'], undefined>;

class EditableTable extends React.Component<any, any> {
  columns: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[];
  columns2: (ColumnTypes[number] & { editable?: boolean; dataIndex: string })[];

  constructor(props: EditableTableProps) {
    super(props);
    this.columns = [
      {
        title: '工单号',
        dataIndex: 'orderId',
      },
      {
        title: '半成品单号',
        dataIndex: 'prepardId',
      },
      {
        title: '物料',
        dataIndex: 'partNum',
      },
      {
        title: '需求量',
        dataIndex: 'needNum',
      },
      {
        title: '已领量',
        dataIndex: 'collectdNum',
      },
      {
        title: '未领量',
        dataIndex: 'uncollectdNum',
      },
      {
        title: '本次领取',
        dataIndex: 'nowcollectdNum',
        editable: true,
      },
    ];
    this.columns2 = [
      {
        title: '领料单号',
        dataIndex: 'orderId',
      },
      {
        title: '半成品单号',
        dataIndex: 'prepardId',
      },
      {
        title: '物料',
        dataIndex: 'partNum',
      },
      {
        title: '需求量',
        dataIndex: 'needNum',
      },
      {
        title: '已领量',
        dataIndex: 'collectdNum',
      },
      {
        title: '未领量',
        dataIndex: 'uncollectdNum',
      },
    ];

    this.state = {
      selectedKeys: [],
      selectedKeys2: [],
      selectedRows: [],
      selectedRows2: [],
      visible: false,

      dataSource: [
        {
          orderId: '0',
          prepardId: '1234443',
          needNum: '112332',
          partNum: '33',
          collectdNum: '89',
          uncollectdNum: '35',
          nowcollectdNum: '20',
        },
      ],
      dataSource2: [
        {
          orderId: '343',
          prepardId: '1234443',
          needNum: '112332',
          partNum: '33',
          collectdNum: '89',
          uncollectdNum: '35',
        },
      ],
      count: 2,
    };
  }
  /**
   * 控制更新模态框显示
   * @param {boolean} visible 是否显示
   */
  switchVisible = (visible = false) => {
    const { selectedRows } = this.state;
    if (selectedRows.length <= 0) {
      message.error('请选择所需物料');
    } else {
      this.setState({
        visible,
      });
    }
  };
  /**
   * @param selectedKeys 选择单元格
   */
  handleRowSelect = (selectedKeys: any, selectedRows: any) => {
    this.setState({
      selectedKeys,
      selectedRows,
    });
  };
  
  handleRowSelect2 = (selectedKeys2: any, selectedRows2: any) => {
    this.setState({
      selectedKeys2,
      selectedRows2,
    });
  };
  /**
   * 确认退料
   * @param selectedRows 
   */
   handleRetreat=(values:any)=>{
    const {selectedRows2} = this.state;
    
    if(selectedRows2.length <=0) {
      message.error('请选择所需退料')
    } else{
      message.success('调用退料接口')
    }
  }
  handleDelete = (key: React.Key) => {
    const dataSource = [...this.state.dataSource];
    this.setState({ dataSource: dataSource.filter((item) => item.key !== key) });
  };

  handleAdd = () => {
    const {  dataSource } = this.state;
   
    this.setState({
      dataSource: [...dataSource,],
    });
  };
  handleAdd2 = () => {
    const {  dataSource2 } = this.state;
  
    this.setState({
      dataSource2: [...dataSource2,],
    });
  };

  handleSave = (row: DataType) => {
    const newData = [...this.state.dataSource];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    this.setState({ dataSource: newData });
  };
  handleSave2 = (row: DataType) => {
    const newData = [...this.state.dataSource2];
    const index = newData.findIndex((item) => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    this.setState({ dataSource2: newData });
  };
  query = () => {
    //接口
  };
  /**
   * @param values 搜索领料信息
   */
  handleSearch = (values: any) => {
    this.setState(
      {
        // params: { ...values },
        // pageNumber: 1,
      },
      this.query,
    );
  };
  /**
   * @param values 搜索领料信息
   */
  handleSearch2 = (values: any) => {
    this.setState(
      {
        // params: { ...values },
        // pageNumber: 1,
      },
      this.query,
    );
  };
  /**
   * 控制新增，编辑事件
   */
  handleSubmit = async (values: any) => {
    // const { dispatch } = this.props;
    // if (editStatus) {
    // await dispatch({
    //   type: '#/edit',
    //   payload,
    // });
    // } else {
    // await dispatch({
    //   type: '#/add',
    //   payload,
    // });
    // }
    this.switchVisible();
    this.query();
  };

  render() {
    const { selectedKeys, dataSource, visible, dataSource2 ,selectedKeys2} = this.state;
    const rowSelection = {
      selectedRowKeys: selectedKeys,
      onChange: this.handleRowSelect,
    };
    const rowSelection2 = {
      selectedRowKeys: selectedKeys2,
      onChange: this.handleRowSelect2,
    };
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: (record: DataType) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    const columns2 = this.columns2.map((col) => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: (record: DataType) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave2,
        }),
      };
    });
    return (
      <PageHeaderWrapper title={false}>
        <Card>
          <Tabs defaultActiveKey="1">
            <TabPane tab={<span>领料</span>} key="1">
              <MfgMtlSearch onSearch={this.handleSearch}>
                <Space>
                  <Button type="primary" onClick={() => this.switchVisible(true)}>
                    确认领料
                  </Button>
                  <Button danger>打印</Button>
                </Space>
              </MfgMtlSearch>
              <Table
                rowKey="orderId"
                components={components}
                rowClassName={() => 'editable-row'}
                bordered
                dataSource={dataSource}
                columns={columns as ColumnTypes}
                rowSelection={rowSelection}
                scroll={{ x: 'max-content' }}
              />
            </TabPane>
            <TabPane tab={<span>退料</span>} key="2">
              <MfgMtiSearchTui onSearch={this.handleSearch2}>
                <Button onClick={this.handleRetreat}>退料</Button>
              </MfgMtiSearchTui>
              <Table
                rowKey="orderId"
                components={components}
                rowSelection={rowSelection2}
                bordered
                dataSource={dataSource2}
                columns={columns2 as ColumnTypes}
                scroll={{ x: 'max-content' }}
              />
            </TabPane>
          </Tabs>
        </Card>
        <MfgMtlUpdate
          visible={visible}
          onCancel={this.switchVisible}
          onSubmit={this.handleSubmit}
        />
      </PageHeaderWrapper>
    );
  }
}
export default EditableTable;
